package com.wfm.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 说明获取写锁时，如果有线程获取读锁，需要等待读锁释放
 */
public class ReadWriteLockExample {
    private static final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private static final ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
    private static final ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
    private static int sharedData = 0;

    public static void main(String[] args) {
        // 线程 t1 进行读操作
        Thread t1 = new Thread(() -> {
            readLock.lock();
            try {
                System.out.println("线程 t1 获取了读锁，开始读取数据: " + sharedData);
                // 模拟读操作耗时
                Thread.sleep(3000);
                System.out.println("线程 t1 读取数据完成，释放读锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                readLock.unlock();
            }
        });

        // 线程 t2 进行写操作
        Thread t2 = new Thread(() -> {
            try {
                // 等待一小段时间，确保 t1 先获取读锁
                Thread.sleep(500);
                System.out.println("线程 t2 尝试获取写锁");
                writeLock.lock();
                try {
                    sharedData++;
                    System.out.println("线程 t2 获取了写锁，完成写操作，数据更新为: " + sharedData);
                } finally {
                    writeLock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}